package pub.xspace.nova.system.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import pub.xspace.nova.common.exception.CommonException;
import pub.xspace.nova.system.domain.SysUser;
import pub.xspace.nova.system.mapper.SysUserMapper;
import pub.xspace.nova.system.service.SysUserService;

/**
 * 用户管理 Service实现类
 * 
 * @author HeJianrong
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	@Override
	public SysUser getById(String id) {
		return sysUserMapper.selectById(id);
	}

	@Override
	public SysUser getByUsername(String username) {
		return sysUserMapper.selectByUsername(username);
	}

	@Override
	public SysUser login(SysUser sysUser) {
		SysUser storeUser = sysUserMapper.selectByUsername(sysUser.getUsername());
		if (ObjectUtil.isNotEmpty(storeUser)) {
			if (sysUser.getPassword().equals(storeUser.getPassword())) {
				return storeUser;
			} else {
				throw new CommonException(500, "账号或密码错误");
			}
		} else {
			throw new CommonException(500, "没有这个用户");
		}
	}

	@Override
	public List<SysUser> getAll(SysUser sysUser) {
		return sysUserMapper.selectByParams(sysUser);
	}

	@Override
	public PageInfo<SysUser> getPage(Integer pageNum, Integer pageSize, SysUser sysUser) {
		PageHelper.startPage(pageNum, pageSize);
		List<SysUser> users = sysUserMapper.selectByParams(sysUser);

		return PageInfo.of(users);
	}

	@Override
	public int save(SysUser sysUser) {
		return sysUserMapper.insert(sysUser);

	}

	@Override
	public int updateById(SysUser sysUser) {
		return sysUserMapper.updateById(sysUser);
	}

	@Override
	public int updatePasswordById(SysUser sysUser) {
		String id = sysUser.getId();
		SysUser dbUser = sysUserMapper.selectById(id);
		if(sysUser.getPassword().equals(dbUser.getPassword())) {
			return sysUserMapper.updatePasswordById(sysUser);
		}else {
			throw new CommonException(500, "原密码错误");
		}
		
	}

	@Override
	public int deleteById(String id) {
		return sysUserMapper.deleteById(id);
	}

	@Override
	public int deleteByIds(List<String> ids) {
		return sysUserMapper.deleteByIds(ids);
	}

}
